// 权限模块

import auth from '@/plugins/auth'
import { isHttp } from '@/utils/validate'
import router, { constantRoutes } from '@/router'
import staticRoutes from '@/router/staticRoutes'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'



const usePermissionStore = defineStore(
    'permission',
    {
      state: () => ({
        routes: [],
        addRoutes: [],
        defaultRoutes: [],
        topbarRouters: [],
        sidebarRouters: []
      }),
      actions: {
        setRoutes(routes) {
          this.addRoutes = routes
          this.routes = constantRoutes.concat(routes)
        },
        setDefaultRoutes(routes) {
          this.defaultRoutes = constantRoutes.concat(routes)
        },
        setTopbarRoutes(routes) {
          this.topbarRouters = routes
        },
        setSidebarRouters(routes) {
          this.sidebarRouters = routes
        },
        generateRoutes() {
          return new Promise((resolve) => {
            // 先过滤出有权限的路由
            const sidebarRoutes = filterAsyncRouter(staticRoutes)
            const rewriteRoutes = filterAsyncRouter(staticRoutes, false, true)
            const defaultRoutes = filterAsyncRouter(staticRoutes)

            // 设置路由数据
            this.setRoutes(rewriteRoutes)
            this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
            this.setDefaultRoutes(constantRoutes.concat(sidebarRoutes))
            this.setTopbarRoutes(defaultRoutes)

            // 清空所有动态路由
            let removeRoutes = router.getRoutes()
            removeRoutes.forEach(route => {
              if (route.name && !constantRoutes.some(cr => cr.name === route.name)) {
                router.removeRoute(route.name)
              }
            })

            // 获取当前已存在的路由名称
            const existingRouteNames = router.getRoutes().map(route => route.name);
            
            // 添加动态路由，避免重复添加
            rewriteRoutes.forEach(route => {
              if (!isHttp(route.path) && !existingRouteNames.includes(route.name)) {
                router.addRoute(route)
              }
            })

            resolve(rewriteRoutes)
          })
        }
        }
      }
    )

// 验证是否有路由权限
function hasPermission(route) {
  // 移除权限验证逻辑，所有路由都返回true
  return true
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    // 验证用户是否具有路由权限
    if (!hasPermission(route)) {
      return false
    }

    if (type && route.children) {
      route.children = filterChildren(route.children)
    }

    // 确保路由路径以'/'开头
    if (!route.path.startsWith('/')) {
      route.path = '/' + route.path
    }

    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'LayoutClean') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      }
    }

    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
      // 如果子路由都被过滤掉了，也过滤掉父路由
      if (route.children.length === 0) {
        return false
      }
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export default usePermissionStore
